package dlb.busstop.activities;

import java.io.IOException;
import java.util.List;

import org.json.JSONException;

import android.annotation.TargetApi;
import android.content.Intent;
import android.graphics.Color;
import android.location.Location;
import android.location.LocationManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.view.View;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.Toast;

import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import com.handmark.pulltorefresh.library.PullToRefreshListView;

import dlb.busstop.R;
import dlb.busstop.data.BusStop;
import dlb.busstop.json.BusStopListGrabber;
import dlb.busstop.json.JSONParser;
import dlb.busstop.utils.StopListViewAdapter;
import dlb.busstop.utils.SuggestionAdapter;
import dlb.busstop.utils.ToastMaker;

public class MainActivityRD extends BaseBusStopActivity {

	public static final String TAG = MainActivity.class.getSimpleName();

	private Menu mMenu;
	private MenuItem mRefresh;
	private SearchView mSearchBox;
	private PullToRefreshListView mBusStopsListView;
	private StopListViewAdapter mBusStopListViewAdapter;
	private double mCurrLatitude;
	private double mCurrLongitude;
	private SuggestionAdapter mSuggestionAdapter;
	private LoadBusStopListTask mBusStopListLoader;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.test_main);

		initialiseView();
		setAdapters();

		startLoadBusStopListTask(10, null);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getSupportMenuInflater().inflate(R.menu.main_activity_menu, menu);
		mMenu = menu;
		mRefresh = menu.findItem(R.id.refresh);
		GPSVisibility();

		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.refresh:
			startLoadBusStopListTask(10, null);
			break;
		case R.id.scan:
			startScan();
			break;
		case R.id.enablegps:
			startActivityForResult(new Intent(
					Settings.ACTION_LOCATION_SOURCE_SETTINGS), 1);
			break;
		case R.id.search:
			if (mSearchBox.getVisibility() != View.VISIBLE)
				mSearchBox.setVisibility(View.VISIBLE);
			else
				mSearchBox.setVisibility(View.GONE);
			break;
		default:
			break;
		}

		return super.onOptionsItemSelected(item);
	}

	@Override
	protected void onRestart() {
		super.onRestart();
		startLoadBusStopListTask(10, null);
		GPSVisibility();
	}

	@Override
	protected void onResume() {
		super.onResume();
		startLoadBusStopListTask(10, null);
		GPSVisibility();
	}

	private void startScan() {
		try {
			Intent intent = new Intent("com.google.zxing.client.android.SCAN");
			intent.putExtra("SCAN_MODE", "QR_CODE_MODE");
			startActivityForResult(intent, QR_REQUEST_CODE);

		} catch (Exception e) {
			Toast.makeText(this, R.string.download_barcode_scanner,
					Toast.LENGTH_SHORT).show();
			Uri marketUri = Uri
					.parse("https://play.google.com/store/apps/details?id=com.google.zxing.client.android");
			Intent marketIntent = new Intent(Intent.ACTION_VIEW, marketUri);
			startActivity(marketIntent);

		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == QR_REQUEST_CODE) {
			if (resultCode == RESULT_OK) {
				String contents = data.getStringExtra("SCAN_RESULT");
				if (contents != null && !contents.toString().equals("")) {
					startLoadBusStopListTask(0, contents);
				}
			}
			if (resultCode == RESULT_CANCELED) {
			}
		} else if (requestCode == 1) {
			if (resultCode == RESULT_OK)
				Toast.makeText(this, data.getDataString(), Toast.LENGTH_SHORT)
						.show();
			GpsEnabled();
		}
	}

	private void GPSVisibility() {
		if (mMenu == null)
			return;
		MenuItem item = mMenu.findItem(R.id.enablegps);
		if (GpsEnabled()) {
			item.setIcon(R.drawable.ic_turned_on_gps);
			item.setTitle(R.string.gps_is_active);
		} else {
			item.setIcon(R.drawable.ic_turned_off_gps);
			item.setTitle(R.string.turn_on_gps);
		}
	}

	@TargetApi(Build.VERSION_CODES.HONEYCOMB)
	public void invalidateActionBar() {
		invalidateOptionsMenu();
	}

	private void initialiseView() {
		mBusStopsListView = (PullToRefreshListView) findViewById(R.id.lvBusStops);
		mBusStopsListView
				.setOnRefreshListener(new OnRefreshListener<ListView>() {

					@Override
					public void onRefresh(
							PullToRefreshBase<ListView> refreshView) {
						mRefresh.setActionView(R.layout.test_layout_progress);
						startLoadBusStopListTask(10, null);
					}
				});
		mSearchBox = (SearchView) findViewById(R.id.swSearch);
		mSearchBox.setActivated(true);
	}

	private void setAdapters() {
		mBusStopListViewAdapter = new StopListViewAdapter(this);
		mBusStopsListView.setAdapter(mBusStopListViewAdapter);
		mSuggestionAdapter = new SuggestionAdapter(this,
				R.layout.layout_autocomplete_resource);
		// mSearchBox.set
	}

	private void startLoadBusStopListTask(int quantity, String SearchKey) {
		if (mBusStopListLoader == null) {
			if (GpsEnabled() || isNetworkEnabled()) {
				mBusStopListLoader = new LoadBusStopListTask(quantity,
						SearchKey);
				mBusStopListLoader.execute();
			}
		}
	}

	public boolean GpsEnabled() {
		LocationManager lm = (LocationManager) getSystemService(LOCATION_SERVICE);
		return lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
	}

	private class LoadBusStopListTask extends
			AsyncTask<Void, Void, List<BusStop>> {

		private static final String TAG = "LoadBusStopListTask";

		private int mQuantity;
		private String mSearchKey;
		private boolean mJsonError;
		private boolean mIOError;
		private boolean mLocationUnavailable;

		public LoadBusStopListTask(int quantity, String searchKey) {
			mQuantity = quantity;
			mSearchKey = searchKey;
		}

		@Override
		protected void onPreExecute() {
			if (mRefresh != null)
				mRefresh.setActionView(R.layout.test_layout_progress);
		}

		@Override
		protected List<BusStop> doInBackground(Void... params) {
			Location location = getCurrentLocation();

			if (location != null) {
				mCurrLatitude = location.getLatitude();
				mCurrLongitude = location.getLongitude();
				JSONParser parser = JSONParser.getInstance();
				BusStopListGrabber busStopListGrabber = BusStopListGrabber
						.getInstance(parser);
				try {
					return busStopListGrabber.grabBusStopList(location,
							mQuantity, mSearchKey);
				} catch (JSONException e) {
					// TODO log
					mJsonError = true;
					return null;
				} catch (IOException e) {
					// TODO log
					mIOError = true;
					return null;
				}
			} else {
				mLocationUnavailable = true;
			}
			return null;
		}

		@Override
		protected void onPostExecute(List<BusStop> stops) {
			mRefresh.setActionView(null);
			mBusStopsListView.onRefreshComplete();
			if (mIOError) {
				ToastMaker.GetToast(MainActivityRD.this, Color.RED,
						"IO Exception").show();
			} else if (mJsonError) {
				ToastMaker.GetToast(MainActivityRD.this, Color.RED,
						"JSon Exception").show();
			} else if (mLocationUnavailable) {
				ToastMaker.GetToast(MainActivityRD.this, Color.YELLOW,
						"Cant get Location").show();
			}
			if (stops != null) {
				mBusStopListViewAdapter.setList(stops);

				ToastMaker.GetToast(MainActivityRD.this, Color.BLUE,
						"Stops grabbed successfully").show();;
			} else {
				ToastMaker.GetToast(MainActivityRD.this, Color.YELLOW,
						"Bus stop list is empty").show();
			}
			mBusStopListLoader = null;
			// TODO: handle the case without internet
		}

	}
}
